/*-
 * Copyright (c) 2009 Jonathan Anderson
 * All rights reserved.
 *
 * WARNING: THIS IS EXPERIMENTAL SECURITY SOFTWARE THAT MUST NOT BE RELIED
 * ON IN PRODUCTION SYSTEMS.  IT WILL BREAK YOUR SOFTWARE IN NEW AND
 * UNEXPECTED WAYS.
 * 
 * This software was developed at the University of Cambridge Computer
 * Laboratory with support from a grant from Google, Inc. 
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <QDebug>

#include <sys/capability.h>
#include <sys/types.h>
#include <sys/procdesc.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <sys/wait.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>

#include <libcapsicum.h>
#include <libuserangel.h>

#include <iostream>

#include "TextEditor.h"

#include <QApplication>
#include <QFile>
#include <QMessageBox>

#include <X11/Xlib.h>
#include <X11/Xauth.h>
#include <xcb/xcb.h>

using namespace std;


extern "C" int _xcb_get_auth_info(int fd, xcb_auth_info_t *info, int display);
int connect_to_X(int*, xcb_auth_info_t*);
int sandbox(int argc, char *argv[]);
struct lc_fdlist* setupFontConfig();


int main(int argc, char *argv[])
{
	if(ld_insandbox()) return sandbox(argc, argv);


	QApplication app(argc, argv);

	struct lc_fdlist *fdlist = setupFontConfig();
	if(!fdlist) fdlist = lc_fdlist_new();


	// connect to X
	int Xfd;
	xcb_auth_info_t xauth;

	if(connect_to_X(&Xfd, &xauth))
		err(EX_SOFTWARE, "Error connecting to X server");

	if(lc_fdlist_add(fdlist, "org.freebsd.capsicum.textcap", "X", "DISPLAY",
	                 Xfd) == -1)
		err(-1, "Error in lc_fdlist_add()");


	int my_fd = open(argv[0], O_RDONLY);
	char *sargv[2] = { (char*) "textcap", NULL };
	struct lc_sandbox *sandbox;

	int ret = lch_startfd(my_fd, "textcap", sargv,
	                      LCH_PERMIT_STDOUT | LCH_PERMIT_STDERR,
	                      fdlist, &sandbox);
	if(ret) err(EX_SOFTWARE, "Error starting sandbox");


	ua_set_client_name("Sandboxed Text Editor");
	int32_t angel = ua_find();
	if(angel < 0) err(EX_SOFTWARE, "Couldn't find user angel");

	int sandsock = -1;
	if(lch_getsock(sandbox, &sandsock)) err(EX_SOFTWARE, "Couldn't getsock");

	struct ua_datum *agent_datum = ua_marshall_string("user-angel", 10);
	if(ua_send(sandsock, agent_datum, &angel, 1) < 0)
	{
		cerr << "Error sending user angel FD: " << errno << " ("
		     << strerror(errno) << ")" << endl;
		return -1;
	}



	struct ua_datum *d = ua_marshall_string(xauth.name, xauth.namelen);
	if(ua_send(sandsock, d, NULL, 0) < 0)
	{
		cerr << "Error sending Xauth name: " << errno << " ("
		     << strerror(errno) << ")" << endl;
		return -1;
	}

	d = ua_marshall_string(xauth.data, xauth.datalen);
	if(ua_send(sandsock, d, NULL, 0) < 0)
	{
		cerr << "Error sending Xauth data: " << errno << " ("
		     << strerror(errno) << ")" << endl;
		return -1;
	}

	QMap<QString,QVariant> settings;

/*
	settings["Xauth name"] =
		QString(QByteArray::fromRawData(xauth.name, xauth.namelen));

	settings["Xauth data"] = QByteArray::fromRawData(xauth.data, xauth.datalen);
*/
	QByteArray bytes;
	QDataStream stream(&bytes, QIODevice::WriteOnly);
	stream << settings;

	d = ua_marshall_bytes(bytes.data(), bytes.length());
	if(ua_send(sandsock, d, NULL, 0) < 0)
		err(-1, "Error sending settings to sandbox");



	int childproc = 0;
	if(lch_getprocdesc(sandbox, &childproc))
		err(EX_SOFTWARE, "Error getting sandbox process descriptor");

	struct pollfd fds[] = {
		{ childproc, POLLHUP | POLLERR, 0}, 
	};

	int count = poll(fds, 1, -1);
	if(count < 0) err(EX_SOFTWARE, "Error polling sandbox descriptor");

	return 0;
}


int connect_to_X(int *Xfd, xcb_auth_info_t *auth)
{
	char *host;
	int display;
	int screen;

	bzero(auth, sizeof(*auth));
	if(xcb_parse_display(NULL, &host, &display, &screen) < 0) return -1;

	if(*host)
	{
		*Xfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(*Xfd < 0) return -1;

		int on = 1;
		setsockopt(*Xfd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));

		struct addrinfo hints, *results, *addr;
		bzero(&hints, sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;

		char service[6];
		int port = 6000 + display;

		snprintf(service, sizeof(service), "%hu", port);
		if(getaddrinfo(host, service, &hints, &results)) return -1;

		for(addr = results; addr; addr = addr->ai_next)
		{
			*Xfd = socket(addr->ai_family, addr->ai_socktype,
			             addr->ai_protocol);

			if(*Xfd < 0)
			{
				close(*Xfd);
				*Xfd = -1;
				continue;
			}

			

           		int on = 1;
         		setsockopt(*Xfd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));

            		if(!connect(*Xfd, addr->ai_addr, addr->ai_addrlen))
			{
				_xcb_get_auth_info(*Xfd, auth, display);
				break;
			}
		}
		freeaddrinfo(results);

		return 0;
	}
	else
	{
		*Xfd = socket(AF_UNIX, SOCK_STREAM, 0);
		if(*Xfd == -1) return -1;

		char sockname[30];
		if(snprintf(sockname, sizeof(sockname), "/tmp/.X11-unix/X%i",
		            display) < 0)
			return -1;

		struct sockaddr_un addr;
		strcpy(addr.sun_path, sockname);
		addr.sun_family = AF_UNIX;

		if(connect(*Xfd, (struct sockaddr*) &addr, sizeof(addr)))
			return -1;

		_xcb_get_auth_info(*Xfd, auth, display);

		return 0;
	}
}

